package com.irdstudio.efp.riskm.api.rest;

/**
 * *
 *
 * @author
 * @version 0.1
 * @date 2019/9/15
 * @since 2019/9/15
 */

import com.alibaba.fastjson.JSON;
import com.irdstudio.basic.framework.core.constant.ApplicationConstance;
import com.irdstudio.basic.framework.core.constant.DataRuleType;
import com.irdstudio.basic.framework.core.constant.PubConstant;
import com.irdstudio.basic.framework.core.constant.ResponseData;
import com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.basic.framework.web.controller.AbstractController;
import com.irdstudio.basic.sequence.service.facade.SequenceService;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.cus.service.facade.CusIndivService;
import com.irdstudio.efp.cus.service.vo.CusIndivVO;
import com.irdstudio.efp.e4a.service.facade.SRoleDataRuleService;
import com.irdstudio.efp.limit.service.facade.LmtPrdContService;
import com.irdstudio.efp.limit.service.vo.LmtPrdContVO;
import com.irdstudio.efp.loan.service.facade.AccLoanService;
import com.irdstudio.efp.loan.service.vo.AccLoanVO;
import com.irdstudio.efp.nls.service.facade.NlsApplyInfoService;
import com.irdstudio.efp.nls.service.vo.NlsApplyInfoVO;
import com.irdstudio.efp.riskm.api.service.RiskmUtilService;
import com.irdstudio.efp.riskm.common.ExcelException;
import com.irdstudio.efp.riskm.common.RiskwarningConstant;
import com.irdstudio.efp.riskm.common.util.ExcelImportUtil;
import com.irdstudio.efp.riskm.service.facade.PspCheckTaskAppService;
import com.irdstudio.efp.riskm.service.facade.PspSpecCheckAppService;
import com.irdstudio.efp.riskm.service.facade.PspSpecCheckCusService;
import com.irdstudio.efp.riskm.service.facade.PspSpecCheckTempService;
import com.irdstudio.efp.riskm.service.vo.PspCheckTaskAppVO;
import com.irdstudio.efp.riskm.service.vo.PspSpecCheckAppVO;
import com.irdstudio.efp.riskm.service.vo.PspSpecCheckCusVO;
import com.irdstudio.efp.riskm.service.vo.PspSpecCheckTempVO;
import com.irdstudio.efp.riskm.service.vo.excelVo.PspSpecCheckCusExcelVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/api")
public class PspSpecCheckCusController extends AbstractController {

    @Autowired
    @Qualifier("pspSpecCheckCusService")
    private PspSpecCheckCusService pspSpecCheckCusService;
    @Autowired
    @Qualifier("sRoleDataRuleService")
    private SRoleDataRuleService sRoleDataRuleService;
    @Autowired
    @Qualifier("pspSpecCheckAppService")
    private PspSpecCheckAppService pspSpecCheckAppService;
    @Autowired
    @Qualifier("nlsApplyInfoService")
    private NlsApplyInfoService nlsApplyInfoService;
    @Autowired
    @Qualifier("cusIndivService")
    private CusIndivService cusIndivService;
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    @Qualifier("accLoanService")
    private AccLoanService accLoanService;
    @Autowired
    @Qualifier("lmtPrdContService")
    private LmtPrdContService lmtPrdContService;
    @Autowired
    @Qualifier("pspSpecCheckTempService")
    private PspSpecCheckTempService pspSpecCheckTempService;

    private static final String CONTENTTYPE = "application/json;charset=UTF-8";

    private static final String MODELNAME = "贷后检查-人工检查发起.xls";

    private static final String SHEETNAME = "贷后检查-人工检查发起";

    private static final String IMPORT_PATH = "/template/inspectimportTemplate.xls";

    private List<String> errorCusIdExcelVOList = new ArrayList<>();

    @Autowired
    private RiskmUtilService riskmUtilService;

    /**
     * 列表数据查询
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/psp/spec/check/cuss", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<List<PspSpecCheckCusVO>> queryPspSpecCheckCusAll(
            @RequestBody PspSpecCheckCusVO vo) {
        List<PspSpecCheckCusVO> outputVo = null;
        // 根据用户角色获取用户权限方案
        Map<String, String> dataRuleTypeMap = sRoleDataRuleService.getDataRuleType(httpRequest.getRequestURI(),
                getUserRoles());
        vo.setPrdCodebyBaseInfo(dataRuleTypeMap == null ? null : dataRuleTypeMap.get(PubConstant.PRD_CODE));
        DataRuleType dataRuleType = DataRuleType
                .getDataRuleType(dataRuleTypeMap == null ? null : dataRuleTypeMap.get(PubConstant.PERMIS_TYPE));
        setUserInfoToVO(vo);
        // 根据权限方案调用不同的方案进行数据查询
        switch (dataRuleType) {
            case Owner:
                outputVo = pspSpecCheckCusService.queryAllOwner(vo);
                break;
            case CurrOrg:
                outputVo = pspSpecCheckCusService.queryAllCurrOrg(vo);
                break;
            case CurrDownOrg:
                outputVo = pspSpecCheckCusService.queryAllCurrDownOrg(vo);
                break;
            default:
                outputVo = pspSpecCheckCusService.queryAllOwner(vo);
                break;
        }
        addBizSernoFlow(outputVo);
        return getResponseData(outputVo);

    }



    /**
     * 根据主键查询详情
     * create luzhaoyu 2019/9/27
     *
     * @return
     */
    @RequestMapping(value = "/psp/spec/check/cus/queryInfo", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<List<PspSpecCheckCusVO>> queryByPk(@RequestBody PspSpecCheckCusVO inPspSpecCheckCusVo) {
        List<PspSpecCheckCusVO> outputVo = pspSpecCheckCusService.queryListCusInfo(inPspSpecCheckCusVo);
        return getResponseData(outputVo);

    }

    /**
     * 新增页面查询  检查名称为 待删除00
     * create luzhaoyu 2019/9/27
     * @return
     */
    @RequestMapping(value = "/psp/spec/check/cus/queryChaNameInfo", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<List<PspSpecCheckCusVO>> queryChknameByPk(@RequestBody PspSpecCheckCusVO inPspSpecCheckCusVo) {
        PspSpecCheckCusVO inVo = new PspSpecCheckCusVO();
        inVo.setChkName(RiskwarningConstant.PSP_CHK_NAME);
        List<PspSpecCheckCusVO> outputVo = pspSpecCheckCusService.queryChkNameIsNull(inVo);
        return getResponseData(outputVo);
    }

    /**
     * 根据主键删除信息
     *
     * @param inPspSpecCheckCusVo
     * @return
     */
    @RequestMapping(value = "/psp/spec/check/cus", method = RequestMethod.DELETE)
    public @ResponseBody
    ResponseData<Integer> deleteByPk(@RequestBody PspSpecCheckCusVO inPspSpecCheckCusVo) {
        int outputVo = pspSpecCheckCusService.deleteByPk(inPspSpecCheckCusVo);
        return getResponseData(outputVo);

    }

    /**
     * 根据任务编号和用户编号删除信息
     * create by luzy  2019/10/11
     * @param inPspSpecCheckCusVo
     * @return
     */
    @RequestMapping(value = "/psp/spec/check/cus/oneInfo", method = RequestMethod.DELETE)
    public @ResponseBody
    ResponseData<Integer> deleteOneInfo(@RequestBody PspSpecCheckCusVO inPspSpecCheckCusVo) {
        String[] cusId = inPspSpecCheckCusVo.getCusId().split(",");
        List<String> cusIds = new ArrayList<>();
        for (int i = 0; i < cusId.length; i++) {
            cusIds.add(cusId[i]);
        }
        inPspSpecCheckCusVo.setCusIds(cusIds);
        int outputVo = pspSpecCheckCusService.deleteOneInfo(inPspSpecCheckCusVo);
        return getResponseData(outputVo);
    }

    /**
     * 批量导入新增
     * luzhaoyu  2019/9/27
     * @param inPspSpecCheckCusVo
     * @return
     */
    @RequestMapping(value = "/psp/spec/check/cus/app/{action}", method = RequestMethod.PUT)
    public @ResponseBody
    ResponseData<Integer> updateByPk(@RequestBody PspSpecCheckCusVO inPspSpecCheckCusVo, @PathVariable("action") String action) {
        int outputVo = 0;
        setUserInfoToVO(inPspSpecCheckCusVo);
        // 根据 bizSerno查询提交的数据
        List<PspSpecCheckCusVO> list = Optional.ofNullable(pspSpecCheckCusService.queryByBizSerno(inPspSpecCheckCusVo.getBizSerno())).orElseGet(ArrayList::new);
        CusIndivVO cusIndivVO = new CusIndivVO();
        for (PspSpecCheckCusVO item : list){
            item.setChkName(inPspSpecCheckCusVo.getChkName());
            //检查任务状态
            if (action.equals("save")) {
                item.setSpecCheckStatus(RiskwarningConstant.SPEC_CHECK_STATUS_00);
            } else if (action.equals("commit")) {
                item.setSpecCheckStatus(RiskwarningConstant.SPEC_CHECK_STATUS_01);
            }
            //检查登记状态
            item.setChkInputSts(RiskwarningConstant.STD_ZX_CHK_STATE_00);
            // 客户经理 主管机构
            cusIndivVO.setCusId(item.getCusId());
            CusIndivVO cusIndiv = cusIndivService.queryByPk(cusIndivVO);
            if(cusIndiv != null){
                if (StringUtils.isNotEmpty(cusIndiv.getCusManager())) {
                    item.setCusManager(cusIndiv.getCusManager());
                }else {
                    item.setCusManager(cusIndiv.getPerformanceOwner());
                }
                if (StringUtils.isNotEmpty(cusIndiv.getMainBrId())) {
                    item.setMainBrId(cusIndiv.getMainBrId());
                }else {
                    item.setMainBrId(cusIndiv.getPerformanceOrg());
                }
            }
            //创建者 修改者 时间
            item.setTaskCreateUser(inPspSpecCheckCusVo.getLoginUserId());
            item.setTaskCreateTime(TimeUtil.getCurrentDateTime());
            item.setLastUpdateUser(inPspSpecCheckCusVo.getLoginUserId());
            item.setLastUpdateTime(TimeUtil.getCurrentDateTime());
            outputVo = pspSpecCheckCusService.updateCusIdByPk(item);
        }
        if (outputVo > 0) {
            PspSpecCheckAppVO pspSpecCheckAppVO = new PspSpecCheckAppVO();
            pspSpecCheckAppVO.setBizSerno(inPspSpecCheckCusVo.getBizSerno());
            pspSpecCheckAppVO.setChkName(inPspSpecCheckCusVo.getChkName());
            pspSpecCheckAppVO.setCreateUser(inPspSpecCheckCusVo.getLoginUserId());
            pspSpecCheckAppVO.setCreateTime(TimeUtil.getCurrentDateTime());
            pspSpecCheckAppVO.setInputBrId(inPspSpecCheckCusVo.getLoginUserOrgCode());
            if (action.equals("save")) {
                pspSpecCheckAppVO.setSpecCheckStatus(RiskwarningConstant.SPEC_CHECK_STATUS_00);
            } else if (action.equals("commit")) {
                pspSpecCheckAppVO.setSpecCheckStatus(RiskwarningConstant.SPEC_CHECK_STATUS_01);
            }
            outputVo = pspSpecCheckAppService.insertPspSpecCheckApp(pspSpecCheckAppVO);
            if (outputVo == -1) {
                //插入cus表成功 app表失败则删除 cus表刚插入的数据
                int num =  pspSpecCheckCusService.deleteByPk(inPspSpecCheckCusVo);
                return setResponseMessage(outputVo, "保存专项检查申请表数据失败！");
            }
            return getResponseData(outputVo);
        }
        return setResponseMessage(outputVo, "保存专项检查客户表数据失败！ ");
    }

    /**
     * create luzhaoyu 2019/9/27
     * @param inPspSpecCheckCusVo
     * @return
     */
    @RequestMapping(value = "/psp/spec/check/cus/app/edit/{action}", method = RequestMethod.PUT)
    public @ResponseBody
    ResponseData<Integer> updateOneInfoByPk(@RequestBody PspSpecCheckCusVO inPspSpecCheckCusVo, @PathVariable("action") String action) {
        int outputVo = 0;
        setUserInfoToVO(inPspSpecCheckCusVo);
        // 根据 bizSerno查询提交的数据
        List<PspSpecCheckCusVO> list = Optional.ofNullable(pspSpecCheckCusService.queryByBizSerno(inPspSpecCheckCusVo.getBizSerno())).orElseGet(ArrayList::new);
        CusIndivVO cusIndivVO = new CusIndivVO();
        for (PspSpecCheckCusVO item : list){
            item.setChkName(inPspSpecCheckCusVo.getChkName());
            //检查任务状态
            if (action.equals("save")) {
                item.setSpecCheckStatus(RiskwarningConstant.SPEC_CHECK_STATUS_00);
            } else if (action.equals("commit")) {
                item.setSpecCheckStatus(RiskwarningConstant.SPEC_CHECK_STATUS_01);
            }
            //检查登记状态
            item.setChkInputSts(RiskwarningConstant.STD_ZX_CHK_STATE_00);
            // 客户经理 主管机构
            cusIndivVO.setCusId(item.getCusId());
            CusIndivVO cusIndiv = cusIndivService.queryByPk(cusIndivVO);
            if(cusIndiv != null){
                item.setCusManager(cusIndiv.getCusManager());
                item.setMainBrId(cusIndiv.getMainBrId());
            }
            //创建者 修改者 时间
            item.setTaskCreateUser(inPspSpecCheckCusVo.getLoginUserId());
            item.setTaskCreateTime(TimeUtil.getCurrentDateTime());
            item.setLastUpdateUser(inPspSpecCheckCusVo.getLoginUserId());
            item.setLastUpdateTime(TimeUtil.getCurrentDateTime());
            outputVo = pspSpecCheckCusService.updateCusIdByPk(item);
        }
        if (outputVo > 0){
            PspSpecCheckAppVO pspSpecCheckAppVO = new PspSpecCheckAppVO();
            pspSpecCheckAppVO.setBizSerno(inPspSpecCheckCusVo.getBizSerno());
            PspSpecCheckAppVO queryPspSpecCheckAppVO = pspSpecCheckAppService.queryByPk(pspSpecCheckAppVO);
            //检查任务名称
            queryPspSpecCheckAppVO.setChkName(inPspSpecCheckCusVo.getChkName());
            //检查任务状态
            if (action.equals("save")) {
                queryPspSpecCheckAppVO.setSpecCheckStatus(RiskwarningConstant.SPEC_CHECK_STATUS_00);
            } else {
                queryPspSpecCheckAppVO.setSpecCheckStatus(RiskwarningConstant.SPEC_CHECK_STATUS_01);
            }
            outputVo = pspSpecCheckAppService.updateByPk(queryPspSpecCheckAppVO);
        }
        return getResponseData(outputVo);
    }

    /**
     * 新增数据
     *
     * @param inPspSpecCheckCusVo
     * @return
     */
    @RequestMapping(value = "/psp/spec/check/cus", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<Integer> insertPspSpecCheckCus(@RequestBody PspSpecCheckCusVO inPspSpecCheckCusVo) {
        int outputVo = pspSpecCheckCusService.insertPspSpecCheckCus(inPspSpecCheckCusVo);
        return getResponseData(outputVo);
    }

    /**
     * 贷后人工检查发起  批量导入选取时 修改批量导入的bizSerno为新增页面的bizSerno
     * create:luzhaoyu  2019-09-12
     * update:luzhoayu  2019/10/12
     */
    @RequestMapping(value = "/psp/spec/check/cus/batchUpdata", method = RequestMethod.PUT)
    public @ResponseBody
    ResponseData<PspSpecCheckCusVO> insertBatchInfo(@RequestBody PspSpecCheckCusVO pspSpecCheckCusVOList) {
        int outputVo = -1;
        //取出从excel导入的数据
        List<PspSpecCheckCusVO> importDatas = new ArrayList<>();
        if (StringUtil.isNullorBank(pspSpecCheckCusVOList.getCusId())){
            importDatas = pspSpecCheckCusService.queryByBizSerno(pspSpecCheckCusVOList.getTempBizNo());
        }else {
            List<String> cusIds = Arrays.asList(pspSpecCheckCusVOList.getCusId().split(",")).stream().map(a->a.trim()).collect(Collectors.toList());
            pspSpecCheckCusVOList.setCusIds(cusIds);
            importDatas = pspSpecCheckCusService.queryImportDatas(pspSpecCheckCusVOList);
        }
        for (PspSpecCheckCusVO item: importDatas) {
            if (!StringUtil.isNullorBank(pspSpecCheckCusVOList.getBizSerno())) item.setBizSerno(pspSpecCheckCusVOList.getBizSerno());
            item.setChkName(RiskwarningConstant.PSP_CHK_NAME);
            outputVo = pspSpecCheckCusService.updateByBizCus(item);
        }
        return getResponseData(importDatas.get(0));
    }

    @RequestMapping(value = "/psp/spec/check/cus/sampleUpdata", method = RequestMethod.PUT)
    public @ResponseBody
    ResponseData<PspSpecCheckCusVO> insertsampleInfo(@RequestBody List<PspSpecCheckCusVO> pspSpecCheckCusVOList) throws Exception {
        PspSpecCheckCusVO pspSpecCheckCusVO = new PspSpecCheckCusVO();

        String bizSerno = sequenceService.getSequence("PSP_CHK_BIZ_SERNO", "null", "null");
        /**
         * @DATE 2019-12-05
         * @AUTHOR WANGLH4
         * @DEC 若未选择数据则默认全选
         * */
        if ("[]".equals(pspSpecCheckCusVOList.toString()) || Objects.isNull(pspSpecCheckCusVOList)) {
            List<PspSpecCheckTempVO> outputVo = pspSpecCheckTempService.queryAllDatas();
            outputVo.forEach(item->{
                PspSpecCheckCusVO tempVO = new PspSpecCheckCusVO();
                tempVO.setCusId(item.getCusId());
                tempVO.setCusName(item.getCusName());
                tempVO.setCertType(item.getCertType());
                tempVO.setCertCode(item.getCertCode());
                pspSpecCheckCusVOList.add(tempVO);
            });
        }
        /*end 2019-12-05*/
        for(int i = 0; i<pspSpecCheckCusVOList.size();i++){
            if (StringUtil.isNullorBank(pspSpecCheckCusVOList.get(i).getBizSerno())) {
                pspSpecCheckCusVOList.get(i).setBizSerno(bizSerno);
                pspSpecCheckCusVO.setBizSerno(bizSerno);
            }else{
                pspSpecCheckCusVO.setBizSerno(pspSpecCheckCusVOList.get(i).getBizSerno());
            }
            String cusId = pspSpecCheckCusVOList.get(i).getCusId();
            pspSpecCheckCusVO.setCusId(cusId);
            PspSpecCheckCusVO pspCusId =  pspSpecCheckCusService.queryCusByPk(pspSpecCheckCusVO);
            if(pspCusId != null){
                logger.info("当前用户 "+ cusId +" 存在于其他的未登记完成的任务中");
                continue;
            }
            pspSpecCheckCusVOList.get(i).setChkName(RiskwarningConstant.PSP_CHK_NAME);
            pspSpecCheckCusVOList.get(i).setChkInputSts(RiskwarningConstant.STD_ZX_CHK_STATE_00);
        }
        int num  = pspSpecCheckCusService.insertPspSpecCheckCusList(pspSpecCheckCusVOList);
        return getResponseData(pspSpecCheckCusVO);
    }
    /**
     * 贷后人工检查发起  下载模板
     * luzhaoyu
     * 2019-09-06
     */
    @RequestMapping(value = "/psp/spec/check/cus/downLoad", method = RequestMethod.GET)
    public @ResponseBody
    ResponseData<String> cusRelCherkModelDownLoad(HttpServletResponse response, HttpServletRequest request) throws IOException {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            response.setContentType(CONTENTTYPE);
            /**
             * getBytes()，需要声明一下读取的编码方式，不然IE浏览器，会出现文件名乱码，谷歌不会
             * 【解决方法】 getBytes("GBK")
             */
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((MODELNAME).getBytes("GBK"), "ISO8859-1"));
            ServletOutputStream out = response.getOutputStream();
            logger.info("下载关联人数据导入模板开始----------------------------");
            bis = new BufferedInputStream(PspSpecCheckCusController.class.getClassLoader().getResourceAsStream(IMPORT_PATH));
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            logger.error("关联人模板文件下载失败：", e);
            return getResponseData(null);
        } finally {
            if (null != bis) {
                bis.close();
            }
            if (null != bos) {
                bos.close();
            }
        }
        logger.info("下载关联人数据导入模板结束。。。。。。。。。。。。。。。。。。。");
        return getResponseData("success!");
    }

    /**
     * 文件导入并解析储存到数据表
     * create luzhaoyu 2019/9/27
     * @author
     * @version
     * @since
     */
    @SuppressWarnings("resource")
    @RequestMapping(value = "/psp/spec/check/cus/upload", method = RequestMethod.POST)
    public void colltResRecordMapUpload(HttpServletResponse respone, HttpServletRequest request) {
        ResponseData<String> result = new ResponseData<>();
        List<File> cusRelCherkMapChecks = new ArrayList<File>();
        respone.setContentType(CONTENTTYPE);
        OutputStream out = null;
        String bizSerno = request.getParameter("bizSerno");
        try {
            out = respone.getOutputStream();
            //获取文件
            cusRelCherkMapChecks = riskmUtilService.getFileList(request);
            if (!cusRelCherkMapChecks.isEmpty()) {
                for (File file : cusRelCherkMapChecks) {
                    /**
                     * 将Excel文件解析成对应实体Bean
                     *
                     * ExcelImportUtil.importExcelAddCus(file, PspSpecCheckCusExcelVO.class);
                     */
                    List<PspSpecCheckCusExcelVO> colltResRecordExcelVOList = ExcelImportUtil.importExcelByClass(file, PspSpecCheckCusExcelVO.class, SHEETNAME);
                    // 空文件校验
                    if(Objects.isNull(colltResRecordExcelVOList) || colltResRecordExcelVOList.isEmpty()){
                        result = result.createData("", ApplicationConstance.FAILURE, "上传文件为空！", false);
                    }else {
                        //检校数据
                        String errStr = "";
                        errStr = checkDatas(colltResRecordExcelVOList);
                        //组装数据
                        List<PspSpecCheckCusVO> inserColltResRecordMap = new ArrayList<PspSpecCheckCusVO>();
                        //执行插入操作
                        bizSerno = execInsertSql(colltResRecordExcelVOList,bizSerno);
                        //错误信息
                        if (!StringUtil.isNullorBank(errStr)) {
                            errStr = "ExcelError:" + errStr;
                            throw new Exception(errStr);
                        }
                        //组装结果
                        result = result.createData(bizSerno, ApplicationConstance.SUCCESS,"上传文件成功！", true);
                    }
                }
            } else {
                throw new ExcelException("获取不到上传的文件！");
            }
        } catch (Exception e) {
            logger.error("文件上传失败,失败原因:", e);
            result = result.createData(bizSerno, ApplicationConstance.FAILURE, e.getMessage(), false);
        } finally {
            String str = JSON.toJSONString(result);
            try {
                out.write(str.getBytes(Charset.forName("UTF-8")));
                out.flush();
                out.close();
            } catch (IOException e) {
                logger.error("关闭数据流OutputStream出错，错误信息为：", e);
            }
        }
    }

    private String checkDatas(List<PspSpecCheckCusExcelVO> colltResRecordExcelVOList) throws Exception {
        int errorRow = 2;
        errorCusIdExcelVOList.clear();
        //记录已存在的某个任务的催收结果数据行
        List<Integer> errorDuplicateRowList = new ArrayList<>();
        //记录用信cusId不存在的历史数据行
        List<Integer> errorCusIdRowList = new ArrayList<>();
        //记录cusId重复的行数
        List<Integer> sameCusIdRowList = new ArrayList<>();
        String errorDuplicateMsg = "";
        Map<Integer, String> errorList = new HashMap<Integer, String>();
        // 校验cusId是否在用信表中有数据
        List<String> cusIdList = new ArrayList<>();
        PspSpecCheckCusVO tempVO = new PspSpecCheckCusVO();
        for (PspSpecCheckCusExcelVO item : colltResRecordExcelVOList){
            if (cusIdList.contains(item.getCusId())){
                sameCusIdRowList.add(errorRow);
                errorCusIdExcelVOList.add(item.getCusId());
            }else{
                if (Objects.isNull(nlsApplyInfoService.queryCusId(item.getCusId())) || nlsApplyInfoService.queryCusId(item.getCusId()).isEmpty()){
                    errorCusIdRowList.add(errorRow);
                    errorCusIdExcelVOList.add(item.getCusId());
                }else{
                    tempVO.setCusId(item.getCusId());
                    List<PspSpecCheckCusVO> pspCusId = pspSpecCheckCusService.queryByCusIdList(tempVO);
                    if (Objects.isNull(pspCusId) || pspCusId.isEmpty()){
                        cusIdList.add(item.getCusId());
                    }else {
                        errorDuplicateRowList.add(errorRow);
                        errorCusIdExcelVOList.add(item.getCusId());
                    }
                }
            }
            errorRow += 1;
        }
        /*if (!Objects.isNull(cusIdList) && !cusIdList.isEmpty()){
            PspSpecCheckCusVO tempVO = new PspSpecCheckCusVO();
            tempVO.setCusIds(cusIdList);
            List<PspSpecCheckCusVO> pspCusId = pspSpecCheckCusService.queryByCusIdList(tempVO);
            for (PspSpecCheckCusExcelVO item : colltResRecordExcelVOList) {
                //检查是否已存在某个任务的催收结果
                for (PspSpecCheckCusVO a: pspCusId) {
                    if (item.getCusId().equals(a.getCusId())) {
                        errorDuplicateRowList.add(errorRow);
                        errorCusIdExcelVOList.add(item.getCusId());
                    }
                }
                errorRow += 1;
            }
        }*/
        //去重
        errorCusIdExcelVOList.stream().distinct().collect(Collectors.toList());
        if (errorCusIdRowList.size()>0) {
            for (Integer integer : errorCusIdRowList) {
                errorDuplicateMsg = "第【" + integer + "】行客户不存在用信记录，跳过该条！";
                logger.info("重复填写：" + errorDuplicateMsg);
                collError(errorList,integer,errorDuplicateMsg);
            }
        }
        if (errorDuplicateRowList.size()>0) {
            for (Integer integer : errorDuplicateRowList) {
                errorDuplicateMsg = "第【" + integer + "】行客户存在于其他的未登记完成的任务中，跳过该条！";
                logger.info("重复填写：" + errorDuplicateMsg);
                collError(errorList,integer,errorDuplicateMsg);
            }
        }
        if (sameCusIdRowList.size()>0) {
            for (Integer integer : sameCusIdRowList) {
                errorDuplicateMsg = "第【" + integer + "】行客户编号重复，跳过该条！";
                logger.info("重复填写：" + errorDuplicateMsg);
                collError(errorList,integer,errorDuplicateMsg);
            }
        }
        //按key值对errorList排序并将value拼接成字符串
        String rs = "";
        rs += sortAndSpliceMap(errorList);
        /*if (!StringUtil.isNullorBank(rs)) {
            rs = "ExcelError:" + rs;
            throw new Exception(rs);
        }*/
        return rs;
    }

    private String sortAndSpliceMap(Map<Integer, String> errorList) {
        String rs = "";
        //取出key值，根据key值排序
        Object[] key = errorList.keySet().toArray();
        Arrays.sort(key);
        //拼接信息
        Iterator ite = errorList.entrySet().iterator();
        while (ite.hasNext()) {
            Map.Entry string = (Map.Entry) ite.next();
            StringBuffer buffer = new StringBuffer();
            if (StringUtil.isNullorBank(rs)) {
                rs = (String) string.getValue();
            } else {
                rs = buffer.append(rs).append(",").append(string.getValue()).toString();
            }
        }
        return rs;
    }

    private void collError(Map<Integer, String> errorList, Integer integer, String str) {
        if (errorList.containsKey(integer)) {
            integer += 1;
            collError(errorList,integer,str);
        } else {
            errorList.put(integer,str);
        }
    }

    private String execInsertSql(List<PspSpecCheckCusExcelVO> colltResRecordExcelVOList,String bizSerno) throws Exception {
        int num = 0;
        if (Objects.nonNull(colltResRecordExcelVOList)) {
            Iterator<PspSpecCheckCusExcelVO> iterator = colltResRecordExcelVOList.iterator();
            if (StringUtil.isNullorBank(bizSerno)){
                bizSerno = sequenceService.getSequence("PSP_CHK_BIZ_SERNO", "null", "null");
            }
            while (iterator.hasNext()) {
                PspSpecCheckCusExcelVO pspSpecCheckCusExcelVO = iterator.next();
                if (errorCusIdExcelVOList.contains(pspSpecCheckCusExcelVO.getCusId())) continue;
                PspSpecCheckCusVO pspSpecCheckCusVO = new PspSpecCheckCusVO();
                pspSpecCheckCusVO.setBizSerno(bizSerno);
//                pspSpecCheckCusVO.setChkName(RiskwarningConstant.PSP_CHK_NAME);
                pspSpecCheckCusVO.setCusId(pspSpecCheckCusExcelVO.getCusId());
                pspSpecCheckCusVO.setCusName(pspSpecCheckCusExcelVO.getCusName());
                pspSpecCheckCusVO.setCertType(pspSpecCheckCusExcelVO.getCertType());
                pspSpecCheckCusVO.setCertCode(pspSpecCheckCusExcelVO.getCertCode());
                pspSpecCheckCusVO.setChkInputSts(RiskwarningConstant.STD_ZX_CHK_STATE_00);
                num = pspSpecCheckCusService.insertPspSpecCheckCus(pspSpecCheckCusVO);
                if (num < 0) {
                    throw new Exception("批量插入数据出错！请检查是否按照模板填写了正确的数据。");
                }
            }
            errorCusIdExcelVOList.clear();
        } else {
            throw new ExcelException("获取数据为空!");
        }
        return bizSerno;
    }


    /**
     * 查询导入的数据
     * create luzhaoyu 2019/9/27
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/psp/spec/check/cus/chknull", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<List<PspSpecCheckCusVO>> queryChkNameIsNull(
            @RequestBody PspSpecCheckCusVO vo) {
        List<PspSpecCheckCusVO> outputVo = pspSpecCheckCusService.queryChkNameIsNull(vo);
        return getResponseData(outputVo);
    }

    /**
     * 批量删除 导入的数据 没使用的数据
     * create luzhaoyu 2019/9/27
     * @param inPspSpecCheckCusVo
     * @return
     */
    @RequestMapping(value = "/psp/spec/check/cus/chkNull", method = RequestMethod.DELETE)
    public @ResponseBody
    ResponseData<Integer> deleteChkNameIsNul(@RequestBody PspSpecCheckCusVO inPspSpecCheckCusVo) {
        int outputVo = pspSpecCheckCusService.deleteChkNameIsNul(inPspSpecCheckCusVo);
        return getResponseData(outputVo);
    }

    /**
     * 删除新增 页面没使用的数据
     * create luzhaoyu 2019/9/27
     * @param inPspSpecCheckCusVo
     * @return
     */
    @RequestMapping(value = "/psp/spec/check/cus/chkName", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<Integer> deleteChkName(@RequestBody PspSpecCheckCusVO inPspSpecCheckCusVo) {
        inPspSpecCheckCusVo.setChkName(RiskwarningConstant.PSP_CHK_NAME);
        int outputVo = pspSpecCheckCusService.deleteChkName(inPspSpecCheckCusVo);
        return getResponseData(outputVo);
    }

    /**
     * 贷后人工检查发起  新增随机样本展示
     * luzhaoyu
     * 2019-09-05
     * */
    @RequestMapping(value = "/apply/infos/sample", method = RequestMethod.POST)
    public @ResponseBody ResponseData<List<PspSpecCheckTempVO>> querySampleAllByPk(@RequestBody NlsApplyInfoVO vo){

        //不查询存在未登记完成的用户信息
        PspSpecCheckCusVO pspSpecCheckCusVO = new PspSpecCheckCusVO();
        pspSpecCheckCusVO.setChkName(RiskwarningConstant.PSP_CHK_NAME);
        List<PspSpecCheckCusVO> listCusId =  pspSpecCheckCusService.querychkInputSts(pspSpecCheckCusVO);
        List<String> cusIds = null;
        if (listCusId.size() > 0) cusIds = listCusId.stream().map(a->a.getCusId()).collect(Collectors.toList());
        vo.setCusIds(cusIds);
        List<NlsApplyInfoVO> rs = nlsApplyInfoService.querySampleAllByPk(vo);

        /**
         * @DATE 2019-12-05
         * @AUTHOR WANGLH4
         * 将随机查询到的数据存入临时表
         * 1、先清空临时表历史数据
         * 2、再进行插入处理
         * */
        int num1 = pspSpecCheckTempService.deleteAllDatas();
        if (num1 < 0) logger.error("清空临时表数据失败！");
        //组装数据
        if (Objects.nonNull(rs)) {
            List<PspSpecCheckTempVO> tempList = assembDatas(rs);
            int num2 = pspSpecCheckTempService.batchInsertDatas(tempList);
            if (num2<0) logger.error("批量插入失败！");
        }
        PspSpecCheckTempVO pspSpecCheckTempVO = new PspSpecCheckTempVO();
        pspSpecCheckTempVO.setPage(vo.getPage());
        pspSpecCheckTempVO.setSize(vo.getSize());
        List<PspSpecCheckTempVO> outputVo = pspSpecCheckTempService.queryDatasByPage(pspSpecCheckTempVO);
        /*end 2019-12-05*/
        return getResponseData(outputVo);
    }
    /**
     * @DATE 2019-12-05
     * @AUTHOR WANGLH4
     * 组装数据
     * */
    private List<PspSpecCheckTempVO> assembDatas(List<NlsApplyInfoVO> outputVo) {
        List<PspSpecCheckTempVO> tempList = new ArrayList<>();
        outputVo.forEach(item->{
            PspSpecCheckTempVO pspSpecCheckTempVO = new PspSpecCheckTempVO();
            pspSpecCheckTempVO.setCusId(item.getCusId());
            pspSpecCheckTempVO.setCusName(item.getCusName());
            pspSpecCheckTempVO.setCertType(item.getCertType());
            pspSpecCheckTempVO.setCertCode(item.getCertCode());
            tempList.add(pspSpecCheckTempVO);
        });
        return tempList;
    }

    private ResponseData<Integer> setResponseMessage(Integer outputVo, String message) {
        ResponseData<Integer> responseData = new ResponseData<Integer>();
        responseData.setMessage(message);
        responseData.setCode(ApplicationConstance.FAILURE);
        responseData.setSuccess(true);
        return responseData;
    }

    @RequestMapping(value="/psp/spec/check/cus/acc/loans", method=RequestMethod.POST)
    public @ResponseBody ResponseData<List<AccLoanVO>> queryAccLoan(@RequestBody  PspSpecCheckCusVO inPspSpecCheckCusVo) {
        List<AccLoanVO> outputVo = null;
        AccLoanVO accLoanVO = new AccLoanVO();
        accLoanVO.setCertCode(inPspSpecCheckCusVo.getCertCode());
        accLoanVO.setCertType(inPspSpecCheckCusVo.getCertType());
        accLoanVO.setPage(inPspSpecCheckCusVo.getPage());
        accLoanVO.setSize(inPspSpecCheckCusVo.getSize());
        accLoanVO.setTotal(inPspSpecCheckCusVo.getTotal());
        outputVo = accLoanService.queryAccLoan(accLoanVO);
        return getResponseData(outputVo);
    }

    /**
     * 贷款总余额，通过证件号码、证件类型查询贷款台账表，获取贷款余额，累计得到
     * @author xiezw
     * @params  * @param null
     * @return
     * @date 2019/10/18 14:28
     * @version 0.1
     */
    @RequestMapping(value="/psp/acc/loan/balance", method=RequestMethod.POST)
    public @ResponseBody ResponseData<BigDecimal> accuLoanBalance(@RequestBody  PspSpecCheckCusVO inPspSpecCheckCusVo) {
        BigDecimal outputVo = BigDecimal.ZERO;
        AccLoanVO accLoanVO = new AccLoanVO();
        accLoanVO.setCertCode(inPspSpecCheckCusVo.getCertCode());
        accLoanVO.setCertType(inPspSpecCheckCusVo.getCertType());
        List<AccLoanVO> accLoanVOS = Optional.ofNullable(accLoanService.queryAccLoanListByCondition(accLoanVO)).orElseGet(ArrayList::new);
        outputVo = accLoanVOS.
                stream().
                map(AccLoanVO::getLoanBalance).
                filter(Objects::nonNull).
                reduce(BigDecimal.ZERO, BigDecimal::add);
        return getResponseData(outputVo);
    }

    /**
     * 授信总额，通过证件号码、证件类型、额度状态为“有效”查询授信协议表，获取授信额度，累计得到
     * @author xiezw
     * @params  * @param null
     * @return
     * @date 2019/10/18 15:33
     * @version 0.1
     */
    @RequestMapping(value="/psp/lmt/amt", method=RequestMethod.POST)
    public @ResponseBody ResponseData<BigDecimal> accuOwnCdt(@RequestBody  PspSpecCheckCusVO inPspSpecCheckCusVo) {
        BigDecimal outputVo = BigDecimal.ZERO;
        LmtPrdContVO lmtPrdContVO = new LmtPrdContVO();
        lmtPrdContVO.setCertCode(inPspSpecCheckCusVo.getCertCode());
        lmtPrdContVO.setCertType(inPspSpecCheckCusVo.getCertType());
        //lmtPrdContVO.setLmtStatus("02");
        List<LmtPrdContVO> lmtPrdContVOs = Optional.ofNullable(lmtPrdContService.qryLmtPrdContByCust(lmtPrdContVO)).orElseGet(ArrayList::new);
        outputVo = lmtPrdContVOs.
                stream().
                filter(lpcVO -> { return ConsoleConstant.LIMIT_STS_02.equals(lpcVO.getLmtStatus()); }).
                map(LmtPrdContVO::getLmtAmt).
                filter(Objects::nonNull).
                reduce(BigDecimal.ZERO, BigDecimal::add);
        return getResponseData(outputVo);
    }

    /**
     * 封装检查登记流水号属性到前端
     * @author xiezw
     * @params  * @param null
     * @return
     * @date 2020/07/08 9:53
     * @version 0.1
     */
    private List<PspSpecCheckCusVO> addBizSernoFlow(List<PspSpecCheckCusVO> pspSpecCheckCusVOS){
        if (Objects.isNull(pspSpecCheckCusVOS) || pspSpecCheckCusVOS.size()<1){
            return null;
        }
        for (PspSpecCheckCusVO item : pspSpecCheckCusVOS){
            List<PspCheckTaskAppVO> querys = pspCheckTaskAppService.queryByConditions(item.getBizSerno(),item.getCusId(),item.getCertCode());
            if (Objects.nonNull(querys) && querys.size()==1){
                item.setBizSernoFlow(querys.get(0).getBizSerno());
            }
        }
        return pspSpecCheckCusVOS;
    }

    @Autowired
    @Qualifier("pspCheckTaskAppService")
    private PspCheckTaskAppService pspCheckTaskAppService;
}
